package com.whx.authorization.util;

import com.whx.authorization.constant.AuthorizationConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 类名：UrlParamUtil
 * 类路径： com.whx.authorization.util.UrlParamUtil
 * 创建者： whx
 * 创建时间： 10/8/18 1:53 PM
 * 项目： authorization_center
 * 描述：
 */
public class UrlParamUtil {

    public static String encodeUrlParam(String param) throws IOException {
        return URLEncoder.encode(param, AuthorizationConstant.ENCODE_CHARSET);
    }

    public static String decodeUrlParam(String param) throws IOException {
        return URLDecoder.decode(param, AuthorizationConstant.ENCODE_CHARSET);
    }

    public static String buildQuery(Map<String, String> params) throws IOException {
        return buildQuery(params, AuthorizationConstant.ENCODE_CHARSET);
    }


    public static String buildRequestUrl(String url, String... queries) {
        if (queries != null && queries.length != 0) {
            StringBuilder newUrl = new StringBuilder(url);
            boolean hasQuery = url.contains("?");
            boolean hasPrepend = url.endsWith("?") || url.endsWith("&");
            String[] arr$ = queries;
            int len$ = queries.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String query = arr$[i$];
                if (!StringUtils.isEmpty(query)) {
                    if (!hasPrepend) {
                        if (hasQuery) {
                            newUrl.append("&");
                        } else {
                            newUrl.append("?");
                            hasQuery = true;
                        }
                    }

                    newUrl.append(query);
                    hasPrepend = false;
                }
            }

            return newUrl.toString();
        } else {
            return url;
        }
    }

    /**
     * 构造Get参数
     * @param params
     * @param charset
     * @return
     * @throws IOException
     */
    public static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (null != params && !params.isEmpty()) {
            StringBuilder query = new StringBuilder();
            Set<Map.Entry<String, String>> entries = params.entrySet();
            boolean hasParam = false;
            Iterator i$ = entries.iterator();
            while(i$.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)i$.next();
                String name = (String)entry.getKey();
                String value = (String)entry.getValue();
                if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
                    if (hasParam) {
                        query.append("&");
                    } else {
                        hasParam = true;
                    }

                    query.append(name).append("=").append(URLEncoder.encode(value, charset));
                }
            }

            return query.toString();
        } else {
            return null;
        }
    }


    public static Map<String, String> parseCookies(String cookies) {
        return parseSecondDimensionString(cookies, ";", "=");
    }

    public static Map<String, String> parseQueryParams(String queryString) {
        return parseSecondDimensionString(queryString, "&", "=");
    }

    /**
     *
     * @param originString
     * @param firstSplit
     * @param secondSplit
     * @return
     */
    private static Map<String, String> parseSecondDimensionString(String originString, String firstSplit, String secondSplit) {
        Map<String, String> result = new HashMap<String, String>();
        if (StringUtils.isNotBlank(originString)) {
            String[] pairs = originString.trim().split(firstSplit);
            if (pairs != null && pairs.length > 0) {
                for (String pair : pairs) {
                    String[] param = pair.split(secondSplit, 2);
                    if (param != null && param.length == 2) {
                        result.put(param[0], param[1]);
                    }
                }
            }
        }
        return result;
    }
}
